<?php

namespace App\Http\Controllers\Shop;

use App\Http\Controllers\ShopController;
use App\Models\Shop\Address;
use App\Models\Shop\Order;
use App\Models\Shop\Store;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class UserController extends ShopController
{
    /*
     * User
     */
    public function getIndex()
    {
        $this->active = 'user';
        $user = $this->user;
        $thumb = parse_url($user->thumb);
        if(isset($thumb['scheme']) && ($thumb['scheme'] == 'http' || $thumb['scheme'] == 'https'))
        {
        }else{
            $user->thumb = action('ImgController@getMember', ['uid' => $user->id, 'sourceName' => $user->thumb, 'size' => '100x100']);
        }
        $storeID = \Illuminate\Support\Facades\Request::cookie('storeID') ? \Illuminate\Support\Facades\Request::cookie('storeID') : 1;

        //获取大学
        $store = Store::where('id', $storeID)->first();
        return view('shopWx.user')->with(['user' => $user, 'store' => $store, 'active' => $this->active]);
    }
    public function getIndexAjax()
    {
        $storeID = \Illuminate\Support\Facades\Request::cookie('storeID') ? \Illuminate\Support\Facades\Request::cookie('storeID') : 1;
        $store = Store::where('id', $storeID)->first();

        $lastTime = $this->user->signTime ? strtotime($this->user->signTime) : false;
        $thisTime = strtotime(date('Y-m-d 00:00:00', time()));
        $signNum = 0;
        if($lastTime)
        {
            if($thisTime - $lastTime < 86400)
                $signNum = $this->user->signNum;
        }
        return json_encode([
            'code'      =>  1,
            'msg'       =>  'success',
            'data'      =>  [
                'storeName'     =>  $store->name.' >',
                'signTip'       =>  $signNum ? '<span class="sign-tip">連続'.$signNum.' 日チェックイン</span>' : ''
            ]
        ]);
    }

    public function getAddress()
    {
        //获取地址
        return view('shopWx.user-address');
    }
    public function getAddressData()
    {
        $storeID = \Illuminate\Support\Facades\Request::cookie('storeID') ? \Illuminate\Support\Facades\Request::cookie('storeID') : 1;
        //获取地址
        $addressData = Address::where('uid', $this->user->id)->where('storeID', $storeID)->orderBy('id', 'desc')->get();
        return json_encode([
            'code'      =>  1,
            'msg'       =>  'success',
            'data'      =>  $addressData
        ]);
    }

    public function getAddressAdd()
    {
        //获取学校
        $store = Store::all();
        return view('shopWx.user-address-add')->with(['store' => $store]);
    }
    public function postAddressAdd(Request $request)
    {
        $verifyArr = [
            'name'          =>  'required',
            'phone'         =>  'required|numeric',
//            'school'        =>  'required',
            'address'       =>  'required|max:255'
        ];
        $v = Validator::make($request->input(),$verifyArr);
        if($v->fails())
        {
            return json_encode([
                'code'          =>  0,
                'msg'           =>  'ご入力情報を確認ください'
            ]);
        }
        $storeID = \Illuminate\Support\Facades\Request::cookie('storeID') ? \Illuminate\Support\Facades\Request::cookie('storeID') : 1;
        $InputData = $request->input();
        $data = [
            'uid'       =>  $this->user->id,
            'name'      =>  $InputData['name'],
            'phone'     =>  $InputData['phone'],
            'address'   =>  $InputData['address'],
            'storeID'   =>  $storeID
        ];
        $check = Address::create($data);
        if ($check)
        {
            $backData = [
                'code'      =>  1,
                'msg'       =>  '追加成功'
            ];
        }else{
            $backData = [
                'code'      =>  0,
                'msg'       =>  '追加失敗'
            ];
        }
        return json_encode($backData);
    }

    public function getAddressEdit($id)
    {
        //获取地址信息
        $address = Address::find($id);
        //获取学校
        $store = Store::all();
        return view('shopWx.user-address-edit')->with(['address' => $address, 'store' => $store]);
    }
    public function postAddressEdit(Request $request, $id)
    {
        $verifyArr = [
            'name'          =>  'required',
            'phone'         =>  'required|numeric',
//            'school'        =>  'required',
            'address'       =>  'required|max:255'
        ];
        $v = Validator::make($request->input(),$verifyArr);
        if($v->fails())
        {
            return json_encode([
                'code'          =>  0,
                'msg'           =>  'ご入力情報を確認ください'
            ]);
        }
        $storeID = \Illuminate\Support\Facades\Request::cookie('storeID') ? \Illuminate\Support\Facades\Request::cookie('storeID') : 1;
        $InputData = $request->input();
        $data = [
            'uid'       =>  $this->user->id,
            'name'      =>  $InputData['name'],
            'phone'     =>  $InputData['phone'],
            'address'   =>  $InputData['address'],
            'storeID'   =>  $storeID
        ];
        $check = Address::where('id', $id)->update($data);
        if ($check)
        {
            $backData = [
                'code'      =>  1,
                'msg'       =>  '更新しました'
            ];
        }else{
            $backData = [
                'code'      =>  1,
                'msg'       =>  '情報無し'
            ];
        }
        return json_encode($backData);
    }


    public function getUserOrder()
    {
        //获取订单信息
        return view('shopWx.user-order');
    }

    public function getUserOrderData(Request $request)
    {
        $page = $request->has('page') ? $request->input('page') : 1;
        $order = DB::table('shop_order')->where('uid', $this->user->id)->where('payState', '!=', 0)->orderBy('id', 'desc');
        if($page)
        {
            $order = $order->skip(($page-1)*10)->take(10);
        }
        $order = $order->get();
        $ajaxCode = $order ? 1 : 0;
        $ajaxMsg = $order ? 'success' : 'error';

        $html = '';
        foreach ($order as $v)
        {
            $state = [
                'color'     =>  'danger',
                'tip'       =>  '支払待'
            ];
            if ($v->payState == 1)
            {
                switch ($v->logisticsState)
                {
                    case 0:
                        $state = [
                            'color'     =>  'info',
                            'tip'       =>  '注文済'
                        ];
                        break;
                    case 1:
                        $state = [
                            'color'     =>  'ing',
                            'tip'       =>  '配達中'
                        ];
                        break;
                    case 2:
                        $state = [
                            'color'     =>  'success',
                            'tip'       =>  '完了'
                        ];
                        break;
                    default:
                        $state = [
                            'color'     =>  'danger',
                            'tip'       =>  'エラー'
                        ];
                }
            }
            $v->orderList = json_decode($v->orderList) ? json_decode($v->orderList) : $v->orderList;
            $html .= '<div class="card"><div class="card-header">日：'.$v->created_at.' <span class="order-type '.$state['color'].'">'.$state['tip'].'</span></div><div class="card-content"><div class="card-content-inner"><div class="list-block"><ul>';
            if(is_string($v->orderList))
            {
                $html .= '<li class="item-content">'.$v->orderList.'</li>';
            }else{
                foreach ($v->orderList as $vv)
                {
                    $html .= '<li class="item-content">';
                    if($vv->thumb != '')
                        $html .= '<div class="item-media"><img src="'.action('ImgController@getPicture', ['sourceName' => $vv->thumb, 'size' => '110x90']).'"></div>';
                    if(isset($vv->discount))
                    {
                        $html .= '<div class="item-inner"><div class="item-title">'.$vv->title.'</div><div class="item-after">'.$vv->discount.' OFF</div></div></li>';
                    }else{
                        $html .= '<div class="item-inner"><div class="item-title">'.$vv->title.' x '.$vv->num.'</div><div class="item-after">'.round($vv->num*$vv->price, 1).' 円</div></div></li>';
                    }
                }
            }
            $html .= '<li class="item-content"><div class="item-inner"><div class="item-title">合计</div><div class="item-after">'.$v->amount.' 円</div></div></li>';
            $html .= '</ul></div></div></div>';
            $html .= '<div class="card-footer">配達時間: '.$v->shopTime.'</div></div>';
        }
        $page++;

        return json_encode([
            'code'      =>  $ajaxCode,
            'msg'       =>  $ajaxMsg,
            'data'      =>  [
                'orderHtml'     =>  $html,
                'page'          =>  $page
            ]
        ]);
    }

    /**
     * 用户等级说明
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getUserLv()
    {
        return view('shopWx.user-lv');
    }

    /**
     * 签到页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getUserSignIn()
    {
        return view('shopWx.user-sign-in');
    }
    public function getSign()
    {
        $thisTime = strtotime(date('Y-m-d 00:00:00', time()));
        $lastTime = $this->user->signTime ? strtotime($this->user->signTime) : false;
        $signNum = 1;
        $signTime = Carbon::now();
        if ($lastTime)
        {
            if ($lastTime < $thisTime)
            {
                if ($thisTime - $lastTime < 86400 && $this->user->signNum < 5)
                {
                    $signNum = $this->user->signNum + 1;
                }
            }elseif($lastTime >= $thisTime && $lastTime < $thisTime + 86400) {
                return json_encode([
                    'code'      =>  0,
                    'msg'       =>  'チェックイン済み！'
                ]);
            }
        }
        $integral = $this->user->integral + $signNum;
        //获取分组规则 升级
        $groupID = $this->user->groupID;
        foreach ($this->memberGroup as $v)
        {
            if($integral >= $v->requireIntegral)
            {
                if($this->memberGroup[$groupID]->lv < $v->lv)
                    $groupID = $v->id;
            }
        }
        $check = DB::table('users')->where('id', $this->user->id)->update(['groupID' => $groupID,'integral' => $integral, 'signNum' => $signNum, 'signTime' => $signTime]);
        $code = $check ? 1 : 0;
        $msg = $check ? '獲得 '.$signNum.'ポイント' : 'エラー';
        return json_encode([
            'code'      =>  $code,
            'msg'       =>  $msg,
            'data'      =>  [
                'signNum'   =>  $signNum,
                'signTime'  =>  date('Y-m-d',strtotime($signTime)),
                'integral'  =>  $integral
            ]
        ]);
    }
}
